<!-- 右侧滚动导航 -->
<template>
  <px-scrollbar class="add-inspect-plan-router">
    <WidgetRouterItem :router-list="routerList" :routerActive="routerActive" @scrollToAnchor="scrollToAnchor" />
  </px-scrollbar>
</template>
<script setup lang="ts">
import { ref, watch, nextTick } from "vue";
import type { ComponentPublicInstance } from "vue";
import WidgetRouterItem from "./WidgetRouterItem.vue";
defineOptions({
  name: "WidgetRouter"
});
type ListItemb = { ref: any; name: string; children?: ListItemb[] };

const props = defineProps<{ routerList: ListItemb[]; scrollbarRef: ComponentPublicInstance | any; scrollTop: number | any; detph?: number | null }>();
const routerActive = ref<string>();
watch(
  () => props.routerList,
  () => {
    if (props.routerList.length > 0) {
      scrollToAnchor(props.routerList[0]);
    } else {
    }
  },
  { immediate: true }
);
watch(
  () => props.scrollTop,
  newVal => {
    if (newVal !== 0 && !newVal) return;
    handleScroll({ scrollTop: newVal });
  }
);

function scrollToAnchor(item) {
  const { ref, name } = item;
  if (ref && ref.scrollIntoView) {
    ref?.scrollIntoView({ behavior: "smooth" });
  } else if (ref?.ref) {
    ref?.ref?.scrollIntoView({ behavior: "smooth" });
  }
  setTimeout(() => {
    // !!!解决动态加载内容滚动位置异常的问题
    if (ref && ref.scrollIntoView) {
      ref?.scrollIntoView({ behavior: "smooth" });
    } else if (ref?.ref) {
      ref?.ref?.scrollIntoView({ behavior: "smooth" });
    }
  }, 100);
  routerActive.value = name;
}
const handleScroll = ({ scrollTop }) => {
  const curScrollTop = scrollTop;
  let flag = true;
  const len = props.routerList.length;
  const min = props.routerList[0]["ref"]!.offsetTop ? props.routerList[0]["ref"]!.offsetTop : props.routerList[0]["ref"]?.ref?.offsetTop;
  if (curScrollTop < min) {
    routerActive.value = props.routerList[0]["name"];
    return;
  }
  let wrapRef = props.scrollbarRef.wrapRef;
  props.scrollbarRef!.moveY = (wrapRef.scrollTop * 100) / wrapRef.clientHeight;
  props.scrollbarRef!.moveX = (wrapRef.scrollLeft * 100) / wrapRef.clientWidth;
  let poor = wrapRef.scrollHeight - wrapRef.clientHeight;
  // 判断滚动到底部
  if (scrollTop + 2 >= poor) {
    routerActive.value = props.routerList[len - 1]["name"];
  } else {
    for (let i = len - 1; i >= 0; i--) {
      const curReference = props.routerList[i]["ref"].offsetTop; // 当前参考值
      if (flag && curScrollTop >= curReference - 50) {
        flag = false;
        routerActive.value = props.routerList[i]["name"];
      }
    }
  }
};
defineExpose({
  handleScroll
});
</script>

<style lang="scss" scoped>
.add-inspect-plan-router {
  flex-shrink: 0;
  width: 200px;
  height: 100%;
  padding-top: 24px;
  margin-left: 17px;
}
</style>
